﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Security.Cryptography;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Net.Mail;

namespace BASE
{
    public class Utils
    {
        public static int getIntQuery(string id)
        {
            int number;
            if (HttpContext.Current.Request.QueryString[id] != null)
            {
                if ((!Int32.TryParse(HttpContext.Current.Request.QueryString[id].ToString(), out number)))
                {
                    return 0;
                }
                return int.Parse(HttpContext.Current.Request.QueryString[id].ToString());
            }
            return 0;
        }
        public static String getStringQuery(string id)
        {

            if (HttpContext.Current.Request.QueryString[id] != null)
            {

                return HttpContext.Current.Request.QueryString[id].ToString();
            }
            return "";
        }
        public static String getStringFrom(string id)
        {

            if (HttpContext.Current.Request.Form[id] != null)
            {

                return HttpContext.Current.Request.Form[id].ToString();
            }
            return "";
        }
        public static int getIntFrom(string id)
        {
            int number;
            if (HttpContext.Current.Request.Form[id] != null)
            {
                if ((!Int32.TryParse(HttpContext.Current.Request.Form[id].ToString(), out number)))
                {
                    return 0;
                }
                return int.Parse(HttpContext.Current.Request.Form[id].ToString());
            }
            return 0;
        }
        public static String getStringSession(String txt)
        {
            if (HttpContext.Current.Session[txt] != null)
            {
                return HttpContext.Current.Session[txt].ToString();
            }
            return "";
        }
        public static int getIntSession(String txt)
        {
            int number;
            if (HttpContext.Current.Session[txt] != null)
            {
                if ((!Int32.TryParse(HttpContext.Current.Session[txt].ToString(), out number)))
                {
                    return 0;
                }
                return Int32.Parse(HttpContext.Current.Session[txt].ToString());
            }
            return 0;
        }

        public static string getMD5(string txt)
        {
            string source = txt;
            MD5 md5 = MD5.Create();
            string hash = GetMd5Hash(md5, source);
            return hash;
        }

        static string GetMd5Hash(MD5 md5Hash, string input)
        {

            // Convert the input string to a byte array and compute the hash. 
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes 
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data  
            // and format each one as a hexadecimal string. 
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string. 
            return sBuilder.ToString();
        }

        // Verify a hash against a string. 
        static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
        {
            // Hash the input. 
            string hashOfInput = GetMd5Hash(md5Hash, input);

            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public static string checkDataType(List<WebControl> lst)
        {
            int number;
            float numbet01;
            foreach (WebControl ctl in lst)
            {
                ctl.BackColor = System.Drawing.Color.White;
                if (ctl is System.Web.UI.WebControls.TextBox)
                {
                    TextBox text = (TextBox)ctl;
                    if (text.Text == "")
                    {
                        ctl.Focus();
                        ctl.BackColor = System.Drawing.Color.Yellow;
                        return "Lỗi không được để trống";
                    }

                    ctl.BackColor = System.Drawing.Color.White;
                }
                if (ctl.Attributes["DataType"] == "integer")
                {
                    if ((!Int32.TryParse(((ITextControl)ctl).Text, out number)))
                    {
                        ctl.Focus();
                        ctl.BackColor = System.Drawing.Color.Yellow;
                        return "loi nhap so lieu";
                    }
                }
                if (ctl.Attributes["DataType"] == "notnull")
                {
                    if (((ITextControl)ctl).Text == "")
                    {
                        ctl.Focus();
                        ctl.BackColor = System.Drawing.Color.Yellow;
                        return "Lỗi không được để trống";
                    }
                }
                if (ctl.Attributes["MaxLength"] != null)
                {
                    int cout = int.Parse(ctl.Attributes["MaxLength"]);
                    if (cout < int.Parse(((ITextControl)ctl).Text))
                    {
                        return "Bạn nhập quá " + cout + " ký tự";
                    }
                }

                if (ctl.Attributes["DataType"] == "float")
                {
                    if ((!float.TryParse(((ITextControl)ctl).Text, out numbet01)))
                    {
                        ctl.Focus();
                        ctl.BackColor = System.Drawing.Color.Yellow;
                        return "loi nhap so lieu";
                    }
                }
                if (ctl.Attributes["DataType"] == "date")
                {
                    string input = ((ITextControl)ctl).Text;
                    DateTime dateTime;
                    var formats = new[] { "dd/M/yyyy", "dd/MM/yyyy", "yyyy-MM-dd" };
                    if (!DateTime.TryParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
                    {
                        ctl.Focus();
                        ctl.BackColor = System.Drawing.Color.Yellow;
                        return "Lỗi nhập ngày tháng";
                    }
                }
                if (ctl.Attributes["DataType"] == "email")
                {
                    Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
                    Match match = regex.Match(((ITextControl)ctl).Text);
                    if (!match.Success)
                    {
                        ctl.Focus();
                        ctl.BackColor = System.Drawing.Color.Yellow;
                        return "Mail không đúng";
                    }
                }
                if (ctl.Attributes["DataType"] == "anh")
                {
                    if (ctl is System.Web.UI.WebControls.FileUpload)
                    {
                        FileUpload file = (FileUpload)ctl;
                        if (file.FileBytes.Length == 0)
                        {
                            file.BackColor = System.Drawing.Color.Yellow;
                            file.Focus();
                            return "chưa chọn file";
                        }
                        string ext = System.IO.Path.GetExtension(file.FileName).TrimStart(".".ToCharArray()).ToLower();
                        if ((ext != "jpeg") && (ext != "jpg") && (ext != "png") && (ext != "gif") && (ext != "bmp"))
                        {
                            file.Focus();
                            file.BackColor = System.Drawing.Color.Yellow;
                            return "lỗi sai định dạng ảnh";
                        }

                    }
                }
                if (ctl.Attributes["DataType"] == "access")
                {
                    if (ctl is System.Web.UI.WebControls.FileUpload)
                    {
                        FileUpload file = (FileUpload)ctl;
                        if (file.FileBytes.Length == 0)
                        {
                            file.BackColor = System.Drawing.Color.Yellow;
                            file.Focus();
                            return "chưa chọn file";
                        }
                        string ext = System.IO.Path.GetExtension(file.FileName).TrimStart(".".ToCharArray()).ToLower();
                        if (ext != "mdb")
                        {
                            file.Focus();
                            file.BackColor = System.Drawing.Color.Yellow;
                            return "lỗi sai định dạng";
                        }

                    }
                }
                if (ctl.Attributes["DataType"] == "xls")
                {
                    if (ctl is System.Web.UI.WebControls.FileUpload)
                    {
                        FileUpload file = (FileUpload)ctl;
                        if (file.FileBytes.Length == 0)
                        {
                            file.BackColor = System.Drawing.Color.Yellow;
                            file.Focus();
                            return "chưa chọn file";
                        }
                        string ext = System.IO.Path.GetExtension(file.FileName).TrimStart(".".ToCharArray()).ToLower();
                        if (ext != "xls")
                        {
                            file.Focus();
                            file.BackColor = System.Drawing.Color.Yellow;
                            return "lỗi sai định dạng";
                        }

                    }
                }
                if (ctl.Attributes["DataType"] == "file")
                {
                    if (ctl is System.Web.UI.WebControls.FileUpload)
                    {
                        FileUpload file = (FileUpload)ctl;
                        if (file.FileBytes.Length == 0)
                        {
                            file.BackColor = System.Drawing.Color.Yellow;
                            file.Focus();
                            return "chưa chọn file";
                        }
                        string ext = System.IO.Path.GetExtension(file.FileName).TrimStart(".".ToCharArray()).ToLower();
                        if ((ext == "exe") || (ext == "dll"))
                        {
                            file.Focus();
                            file.BackColor = System.Drawing.Color.Yellow;
                            return "lỗi sai định dạng ảnh";
                        }

                    }
                }
                if (ctl.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")
                {
                    DropDownList drop = (DropDownList)ctl;
                    if (drop.SelectedValue == "0")
                    {
                        ctl.Focus();
                        ctl.BackColor = System.Drawing.Color.Yellow;
                        return "Lỗi không được để trống";
                    }
                    ctl.BackColor = System.Drawing.Color.White;
                }
                if (ctl.GetType().ToString() == "System.Web.UI.WebControls.CheckBoxList")
                {
                    CheckBoxList drop = (CheckBoxList)ctl;
                    if (drop.SelectedValue == "")
                    {
                        ctl.Focus();
                        ctl.BackColor = System.Drawing.Color.Yellow;
                        return "Lỗi không được để trống";
                    }
                    ctl.BackColor = System.Drawing.Color.White;
                }

            }
            return "";
        }
        public string sendMail(string mail_nguoi_gui, string ten_nguoi_gui, string tieu_de, String noi_dung, string mail_nguoi_nhan)
        {

            DateTime localTime = DateTime.Now;
            string timeString24Hour = localTime.ToString("HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
            System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
            string body = "test send mail1" + timeString24Hour;
            string host = "";
            int post = 0;
            post = 587;
            host = "mail.dtctech.com.vn";
            string cc = "phuoc.nuce@gmail.com";
            mailMessage.From = (new System.Net.Mail.MailAddress("phuoc@dtctech.com.vn", "CDQN", System.Text.Encoding.UTF8));
            mailMessage.To.Add(mail_nguoi_nhan);

            //mailMessage.To.Add(mail_nguoi_gui);


            // mailMessage.Bcc.Add(cc);

            mailMessage.Subject = tieu_de;
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            mailMessage.IsBodyHtml = true;
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential();
            mailAuthentication.UserName = "phuoc@dtctech.com.vn";
            mailAuthentication.Password = "Abc12345a";
            SmtpClient mailClient = new SmtpClient("mail.dtctech.com.vn");
            mailClient.EnableSsl = false;
            mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            mailClient.Credentials = mailAuthentication;
            mailMessage.Body = noi_dung;
            try
            {
                mailClient.Send(mailMessage);

            }
            catch
            {
                return "";
            }
            return "2";
        }
        public static string SendMail(string tomail, string subject)
        {
            MailMessage message = new MailMessage();
            SmtpClient smtpClient = new SmtpClient();
            string msg = string.Empty;
            try
            {
                MailAddress fromAddress = new MailAddress("congsinhvien@dhpd.edu.vn");
                message.From = fromAddress;
                message.To.Add(tomail);

                message.Subject = "Quên mật khẩu";
                message.IsBodyHtml = true;
                message.Body = subject;
                smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
                smtpClient.Port = 587;
                smtpClient.EnableSsl = true;
                smtpClient.UseDefaultCredentials = true;
                smtpClient.Credentials = new System.Net.NetworkCredential("congsinhvien@dhpd.edu.vn", "phuoc12345");

                smtpClient.Send(message);
                msg = "Successful<BR>";
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }
        public static string SendMail(List<String> tomail, string subject, string body)
        {
            MailMessage message = new MailMessage();
            SmtpClient smtpClient = new SmtpClient();
            string msg = string.Empty;
            try
            {
                MailAddress fromAddress = new MailAddress("congsinhvien@dhpd.edu.vn");
                message.From = fromAddress;
                foreach (string item in tomail)
                {
                    message.To.Add(item);
                }
                // message.To.Add("hongphuoc8912@gmail.com");
                message.Subject = subject;
                message.IsBodyHtml = true;
                message.Body = body;
                smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
                smtpClient.Port = 587;
                smtpClient.EnableSsl = true;
                smtpClient.UseDefaultCredentials = true;
                smtpClient.Credentials = new System.Net.NetworkCredential("congsinhvien@dhpd.edu.vn", "phuoc12345");

                smtpClient.Send(message);
                msg = "Successful<BR>";
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }
        public static string SendMail(List<String> tomail, string body)
        {
            MailMessage message = new MailMessage();
            SmtpClient smtpClient = new SmtpClient();
            string msg = string.Empty;
            try
            {
                MailAddress fromAddress = new MailAddress("congsinhvien@dhpd.edu.vn");
                message.From = fromAddress;
                foreach (string item in tomail)
                {
                    message.To.Add(item);
                }
                // message.To.Add("hongphuoc8912@gmail.com");
                message.Subject = "Thắc mắc điểm" + DateTime.Now.ToString("ddmmyyhh");
                message.IsBodyHtml = true;
                message.Body = body;
                smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
                smtpClient.Port = 587;
                smtpClient.EnableSsl = true;
                smtpClient.UseDefaultCredentials = true;
                smtpClient.Credentials = new System.Net.NetworkCredential("congsinhvien@dhpd.edu.vn", "phuoc12345");
                smtpClient.Send(message);
                msg = "Successful<BR>";
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }
        public static string GetUniqueKey(int maxSize)
        {
            char[] chars = new char[62];
            chars =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            byte[] data = new byte[1];
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            data = new byte[maxSize];
            crypto.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder(maxSize);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }
        public static void Messenbox(Literal pa, string noidung)
        {
            String html = "<div id=\"mebox\">";
            html += "    <a href=\"#\">";
            html += "      <div class=\"mebox-main\">";
            html += "          <div class=\"awidget2\">";
            html += "              <div class=\"awidget-head\">";
            html += "                  <h3>";
            html += "                      Thông báo</h3>";
            html += "              </div>";
            html += "            <div class=\"awidget-body no-table-bor\">";
            html += "                <a href=\"#\">noidung</a>";
            html += "            </div>";
            html += "        </div>";
            html += "  </a>";
            html += "  </div>";
            pa.Text = html;
        }
    }
}
